package net.starwifi.duobao.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * Created by Administrator on 2015/7/30.
 */
public class DesHelper {

    private static String mode="DES/ECB/PKCS5Padding";
    private static String key = "08bf46321f863ea1";

    public static String decrypt(String message) throws Exception {
        byte[] bytesrc = convertHexString(message);
        Cipher cipher = Cipher.getInstance(mode);
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        byte[] retByte = cipher.doFinal(bytesrc);
        return new String(retByte,"UTF-8");
    }


    public static byte[] encrypt(String message) throws Exception {
        Cipher cipher = Cipher.getInstance(mode);

        //  DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
        DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
        //IvParameterSpec iv = new IvParameterSpec(new byte[]{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
        //cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);

        return cipher.doFinal(message.getBytes("UTF-8"));
    }

    public static byte[] convertHexString(String ss) {
        byte digest[] = new byte[ss.length() / 2];
        for (int i = 0; i < digest.length; i++) {
            String byteString = ss.substring(2 * i, 2 * i + 2);
            int byteValue = Integer.parseInt(byteString, 16);
            digest[i] = (byte) byteValue;
        }

        return digest;
    }

    public static String toHexString(byte b[]) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            String plainText = Integer.toHexString(0xff & b[i]);
            if (plainText.length() < 2)
                plainText = "0" + plainText;
            hexString.append(plainText);
        }

        return hexString.toString();
    }



    public static void main(String[] args) {
        try {
            String text = "张三&420923199010053358&13018070647";
            System.out.println("明文:" + text);
            String cryperText = "";
            cryperText = toHexString(encrypt(text));
            System.out.println("加密后:" + cryperText);
            System.out.println("解密后:" + decrypt(cryperText));

            //加密
            String s=DesHelper.toHexString(DesHelper.encrypt("18671725223"));
            System.out.println(s);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



}
